// templates/deliver/pages/location/location.js
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
import Dialog from '@vant/weapp/dialog/dialog';
import { clearUserLocalStorage } from "../../../../utils/util";
function debounce(func, delay) {
    let timer = null;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}
const app = getApp();
Page({

    data: {
        upload_text: '',
        // buttonDisabled: false,
        id: 0,
        username: '',
        customer_list: [],
        customer_value: -1,
        search_mobile: '',
        customer_id: 0,
        customer_name: '',
        customer_mobile: '',
        price: 0,
        order_no: '',
        view_delivery_man_id: 0,
        view_driver_name: '',
        view_delivery_district_id: 0,
        tempFilePaths: [],
        address: '',
        customer_remark: '',
        delivery_man_id: 0,


    },


    // generateOrderNo(delivery_man_id) {
    //     const date = new Date()
    //     const year = date.getFullYear()
    //     const month = date.getMonth() + 1 // 月份从 0 开始计数，所以需要加 1
    //     const day = date.getDate()
    //     const h = date.getHours()
    //     const m = date.getMinutes()
    //     const s = date.getSeconds()

    //     let formattedDate = `${year.toString().padStart(4, '0')}${month.toString().padStart(2, '0')}${day.toString().padStart(2, '0')}`
    //     //formattedDate += `${h.toString().padStart(2, '0')}${m.toString().padStart(2, '0')}${s.toString().padStart(2, '0')}`
    //     const randomNumber = Math.floor(Math.random() * 1000);
    //     const order_no = `XD${formattedDate}${delivery_man_id.toString().padStart(4, '0')}${randomNumber.toString().padStart(3, '0')}`
    //     return order_no
    // },

    /**
     * 生命周期函数--监听页面加载
     */

    onLoad(options) {
        let now = new Date().getTime() / 1000
        let expiration_time = wx.getStorageSync('expiration_time')
        let group = wx.getStorageSync('role')
        console.log('session:', app.session)
        // wx.setStorageSync('viewDeliveryDate', new Date())
        let access_token = app.session.access_token
        let delivery_man_id = app.session.user.delivery_man_id
        let level = wx.getStorageSync('level')
        console.log(app.session.user.delivery_man_id)
        console.log(delivery_man_id)

        // 调用检查登录状态的函数
        this.checkLoginStatus(now, expiration_time, group, level)
        this.setData({
            access_token,
            delivery_man_id,
            level,
            order_no: this.generateOrderNo()
        })
        //如果登录缓存过期就跳转登录页面
        // let now = (new Date().getTime()) / 1000;
        // let expiration_time = wx.getStorageSync('expiration_time')
        // let group = wx.getStorageSync('role')
        // if (now > expiration_time) {
        //     console.log('已过登录有效期!');
        //     app.session = {};
        //     clearUserLocalStorage();
        //     wx.reLaunch({
        //         url: '/pages/selectID/selectID',
        //     });
        // }
        // if (group !== '配送司机') {
        //     clearUserLocalStorage()
        //     expiration_time = 0
        // }
        // let access_token = wx.getStorageSync('access_token')
        // let delivery_man = app.session.delivery_man
        // let delivery_district = app.session.delivery_district
        // let delivery_district_list = app.session.delivery_district_list
        // let delivery_list = app.session.delivery_list


        // let view_delivery_man_id = app.session.view_delivery_man_id || 0
        // let view_driver_name = ''
        // let view_delivery_district_id = 0
        // if (view_delivery_man_id > 0) {
        //     view_driver_name = app.session.view_driver_name
        //     view_delivery_district_id = app.session.view_delivery_district_id
        // }


        // let delivery_man_id = delivery_man.delivery_man_id
        // let current_delivery_man_id = app.session.current_delivery_man_id
        // if (!current_delivery_man_id || current_delivery_man_id == 0) {
        //     current_delivery_man_id = 0
        // }
        // let order_no = this.generateOrderNo(delivery_man_id)
        // this.setData({
        //     order_no: order_no,
        //     delivery_man_id: delivery_man_id,
        // })

        // /*if (now > expiration_time) {
        //     wx.reLaunch({
        //         url: '/pages/selectID/selectID',
        //     })
        // }*/


        // this.setData({
        //     'access_token': access_token,
        //     'delivery_man': delivery_man,
        //     'delivery_district': delivery_district,
        //     'delivery_district_list': delivery_district_list,
        //     'delivery_list': delivery_list,
        //     'current_delivery_district_id': 0,
        //     'level': delivery_man.level,
        //     'current_delivery_man_id': current_delivery_man_id,
        //     view_delivery_man_id,
        //     view_driver_name,
        //     view_delivery_district_id
        // })
    },
    checkLoginStatus(now, expiration_time, group, level) {
        console.log(level)
        console.log(level !== '1' && level !== '9')
        if (group !== '配送司机' || now > expiration_time) {
            let groupName = group.name !== '配送司机' ? '非配送司机角色！' : '已过登录有效期!'
            wx.showToast({
                title: groupName,
                icon: 'error',
                duration: 2000
            })
            app.session = {}
            clearUserLocalStorage()
            setTimeout(() => {
                wx.reLaunch({
                    url: '/pages/selectID/selectID'
                })
            }, 1000)
        }
    },
    generateOrderNo() {
        const date = new Date();
        const prefix = "XD";
        // 日期部分：年月日（6位）
        const year = date.getFullYear().toString().slice(2); // 2位
        const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 2位
        const day = date.getDate().toString().padStart(2, '0'); // 2位

        // 时间部分：时（2位）
        const hour = date.getHours().toString().padStart(2, '0'); // 2位

        // 随机数：4位
        const randomPart = Math.floor(Math.random() * 10000).toString().padStart(4, '0'); // 0000 ~ 9999
        const order_no = `${prefix}${year}${month}${day}${hour}${randomPart}`.slice(0, 14)
        return order_no; // 保证14位

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {



    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {



    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },
    onCustomerChange: debounce(function (e) {
        const field = e.currentTarget.dataset.field;
        const value = e.detail;
        console.log(field, value)
        // 使用对象解构动态更新数据
        const data = {};
        data[field] = value;
        this.setData(data);
    }, 300),
    onPriceChange(e) {
        let price = e.detail
        this.setData({
            price: price
        })
    },

    onCustomerNameChange(e) {
        let customer_name = e.detail
        this.setData({
            customer_name: customer_name
        })
        this.searchCustomer(customer_name, '')

    },
    onCustomerMobileSearchChange(e) {
        let search_mobile = e.detail.replace(/\s+/g, '');
        // 验证手机号格式
        let mobilePattern = /^1[3-9]\d{9}$/;
        if (!mobilePattern.test(search_mobile)) {
            Toast.fail('请输入正确的手机号');
            return;
        }
        this.setData({
            search_mobile: search_mobile,
            customer_mobile: search_mobile
        });

        // 清除之前的防抖计时器
        if (this.data.debounceTimeout) {
            clearTimeout(this.data.debounceTimeout);
        }

        // 设置新的防抖计时器
        this.data.debounceTimeout = setTimeout(() => {
            this.searchCustomer('', search_mobile);
        }, 1000); // 300 毫秒的防抖时间
    },
    // onCustomerMobileChange(e) {
    //     let customer_mobile = e.detail
    //     this.setData({
    //         customer_mobile
    //     })
    // },



    searchCustomer(customer_name, search_mobile) {
        let that = this;
        wx.request({
            url: app.globalData.API + '/delivery/index/search-customer',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": that.data.access_token,
            },
            data: {
                customer_name,
                search_mobile,
            },
            method: "POST",
            success: res => {
                if (res.data.code === 200) {
                    const success = res.data.data;
                    console.log(success)
                    if (success) {
                        let customer_list = res.data.data;
                        let customer_value = -1;
                        let customer_id = 0;
                        let customer_mobile = '';
                        let address = '';
                        if (customer_list && (customer_list.length > 0)) {
                            customer_list = customer_list.map((customer) => {
                                customer.text = `[Id: ${customer.value}] ${customer.text}`;
                                return customer;
                            });
                            console.log(customer_list[0].addresses[0].location)
                            if (customer_list[0].addresses[0].location) {
                                console.log("地址不为空")
                                address = customer_list[0].addresses[0].location
                            } else {
                                address = customer_list[0].addresses[0].city + customer_list[0].addresses[0].district + customer_list[0].addresses[0].detail
                            }
                            customer_value = customer_list[0].value // 将第一个数据显示为选中项
                            customer_name = customer_list[0].addresses[0].name
                            customer_mobile = customer_list[0].mobile
                            customer_id = customer_list[0].value
                        } else {
                            customer_mobile = search_mobile
                        }
                        that.setData({
                            customer_list: customer_list,
                            customer_value: customer_value,
                            customer_id,
                            customer_name,
                            customer_mobile,
                            address
                        });
                    }
                }
            }
        });
    },

    on_dropdown_customer_change(e) {
        let current_customer_value = e.detail
        let that = this
        // 遍历数组
        for (let i = 0; i < that.data.customer_list.length; i++) {
            // 获取当前元素
            const customer = that.data.customer_list[i];

            // 比较 value 属性
            if (customer.value === current_customer_value) {
                that.setData({
                    customer_value: current_customer_value,
                    customer_name: customer.text,
                    customer_mobile: customer.mobile,
                    customer_id: current_customer_value
                })
            }
        }


        //wx.setStorageSync('current_month', current_month)
        //this.get_statistics().then(r => {})
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    formSubmit(e) {

        let that = this
        // if (that.data.buttonDisabled) {
        //     return
        // }
        const { delivery_man_id, order_no, customer_name, customer_mobile, customer_id, price, address, customer_remark } = this.data;
        // 验证手机号格式是否正确

        if (price <= 0) {
            wx.showToast({
                title: '请输入商户金额:',
                icon: 'none'

            }).then(() => {
                // on close
                console.log('then')
            });
            return;
        }
        let tempFilePaths = that.data.tempFilePaths;

        if (tempFilePaths.length > 0) {
            const filePath = tempFilePaths[0].url;
            wx.uploadFile({
                //url: 'https://helper.fuduoduoshop.com/api/v1/file/images?access-token=' + this.data.access_token,
                url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
                filePath: filePath, //传递文件
                header: {
                    'Content-Type': 'application/json',
                    "x-api-key": this.data.access_token,
                },
                name: 'file', //获取照片信息的名称
                formData: {
                    drive: 'qiniu',
                    thumb: JSON.stringify([{
                        width: 100,
                        height: 100
                    }])
                },

                success(res) {
                    let response = JSON.parse(res.data) //传过来的是json 需要转换成对象
                    let code = response.code
                    if (code === 200) {
                        let mall_id = app.globalData.mall_id;
                        wx.request({
                            url: app.globalData.API + '/delivery/index/add-offline-delivery-order',
                            header: {
                                'Content-Type': 'application/json',
                                "x-api-key": that.data.access_token,
                            },
                            method: "POST",
                            data: {
                                order_no: order_no,
                                customer_name: customer_name,
                                customer_mobile: customer_mobile,
                                customer_id: customer_id,
                                price: price,
                                channel_id: mall_id,
                                delivery_man_id: delivery_man_id,
                                image_id: response.data.id,
                                image_url: response.data.url,
                                address: address,
                                customer_remark: customer_remark
                            },
                            success(result) {
                                that.setData({
                                    'upload_text': '上传成功'
                                })
                                Toast.success('订单添加完成');
                                // Notify({ type: 'success', message: '订单添加完成' });
                                setTimeout(function () {
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                }, 1000);
                            }
                        });
                    }
                }
            })
        } else {
            Toast.fail('请先拍照或者选择照片~~');
        }

    },
    imgSize(event) {
        let imgMax = this.data.address_image_max_size; //获取默认上传文件大小
        const {
            file
        } = event.detail; //获取上传文件数组
        for (let i = 0; i < file.length; i++) {
            if (file[i].size > imgMax) {
                Toast('大小超过2MB~')
            }
        }
    },

    /* 上传文件后事件，处理照片放入OSS回显 */
    afterRead(event) {
        let that = this
        const { file } = event.detail;
        this.setData({
            tempFilePaths: [...this.data.tempFilePaths, { url: file.url }]
        })
        console.log(this.data.tempFilePaths)
        // this.unloadImage(file.path)
        for (let i = 0; i < file.length; i++) {
            wx.uploadFile({
                url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
                filePath: file[i]['url'], //传递文件
                header: {
                    'Content-Type': 'application/json',
                    "x-api-key": that.data.access_token,
                },
                name: 'file', //获取照片信息的名称
                formData: {
                    drive: 'qiniu',
                    thumb: JSON.stringify([{
                        width: 100,
                        height: 100
                    }])
                },

                success(res) {
                    let response = JSON.parse(res.data) //传过来的是json 需要转换成对象
                    let code = response.code
                    if (code === 200) {
                        const { tempFilePaths = [] } = that.data;
                        tempFilePaths.push({ ...file, url: response.data.url })
                        that.setData({
                            tempFilePaths
                        })
                    }
                }
            })
        }
    },
    // uploadImage(filePath){


    // },

    imgDelete(event) {
        let that = this;
        let urlPath = event.detail.file.url
        wx.request({
            url: app.globalData.API + '/delivery/index/delete-qiniu-image',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": that.data.access_token,
            },
            data: {
                path: urlPath
            },
            method: "POST",
            success: res => {
                if (res.data.code === 200) {
                    const success = res.data.data;
                    console.log(success)
                    if (success) {
                        let tempFilePaths = that.data.tempFilePaths
                        tempFilePaths = tempFilePaths.filter(item => item.url !== urlPath);
                        that.setData({
                            tempFilePaths
                        })
                    }
                }
            }
        });
    },

    // chooseImage: function () {
    //     var _this = this;
    //     wx.chooseImage({
    //         count: 1, // 默认9
    //         sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    //         sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    //         success: function (res) {
    //             //console.log(res.tempFilePaths)
    //             // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
    //             _this.setData({
    //                 tempFilePaths: res.tempFilePaths
    //             })
    //         }
    //     })
    // },
})
